package com.dingding.mid.listener;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.dingding.mid.dto.json.ChildNode;
import com.dingding.mid.dto.json.Properties;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.Process;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.delegate.JavaDelegate;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.util.List;

import static com.dingding.mid.common.WorkFlowConstants.*;
import static com.dingding.mid.utils.BpmnModelUtils.getChildNode;

/**
 * @author LoveMyOrange
 * @create 2022-10-15 19:47
 */
@Component
@Slf4j
public class TimerListener implements JavaDelegate {
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private TaskService taskService;
    @Resource
    private RuntimeService runtimeService;

    /**
     * 自行编写 触发逻辑既可
     * @param execution
     */
    @Override
    public void execute(DelegateExecution execution) {
        ChildNode childNode = getNode(execution);
        String currentActivityId = execution.getCurrentActivityId();
        String[] split = currentActivityId.split("---");
        String nodeId=split[0];
        ChildNode node = getChildNode(childNode, nodeId);
        System.err.println(node);
        String processInstanceId = execution.getProcessInstanceId();
        Properties props = node.getProps();
        JSONObject timeLimit = props.getTimeLimit();
        JSONObject handler = timeLimit.getJSONObject("handler");
        String type = handler.getString("type");
        if("PASS".equals(type)){
            List<Task> list =
                    taskService.createTaskQuery().processInstanceId(processInstanceId).taskDefinitionKey(nodeId).list();
            if(CollUtil.isNotEmpty(list)){
                for (Task task : list) {
                    taskService.addComment(task.getId(),task.getProcessInstanceId(),OPINION_COMMENT,"审批超时自动通过");
                    taskService.complete(task.getId());
                }
            }
        }
        else if("REFUSE".equals(type)){
            runtimeService.deleteProcessInstance(execution.getProcessInstanceId(),"超时自动驳回");
        }
        else if("NOTIFY".equals(type)){
            //todo提醒逻辑
            System.err.println("进入执行");
        }
    }
    private ChildNode getNode(DelegateExecution execution) {

        Process mainProcess = repositoryService.getBpmnModel(execution.getProcessDefinitionId()).getMainProcess();
        String dingDing = mainProcess.getAttributeValue(FLOWABLE_NAME_SPACE, FLOWABLE_NAME_SPACE_NAME);
        JSONObject jsonObject = JSONObject.parseObject(dingDing, new TypeReference<JSONObject>() {
        });
        String processJson = jsonObject.getString(VIEW_PROCESS_JSON_NAME);
        ChildNode childNode = JSONObject.parseObject(processJson, new TypeReference<ChildNode>(){});
        return childNode;
    }
}
